using System;
using System.Collections;
using System.Diagnostics;
using UnityEngine;

public class TSingleton<T> : SingletonBase where T : class
{
    public static bool IsSingletonCreated
    {
        get
        {
            return (TSingleton<T>.ms_Singleton != null);
        }
    }

    private static T ms_Singleton;
    public static T Singleton
    {
        get
        {
            if (TSingleton<T>.ms_Singleton == null)
            {
                TSingleton<T>.InstantiateMissingSingleton(typeof(T));
            }
            return TSingleton<T>.ms_Singleton;
        }
    }

    //--------------------------------------------------------------------------------------------

    protected virtual void Awake()
    {
        if (TSingleton<T>.ms_Singleton == null)
        {
            TSingleton<T>.ms_Singleton = ((TSingleton<T>)this) as T;
        }
        else if (TSingleton<T>.ms_Singleton != this as T)
        {
            Destroy(base.gameObject);
            return;
        }

        DontDestroyOnLoad(this);
    }

    protected sealed override void Start()
    {
        this.SingletonStart();
    }

    protected virtual void SingletonStart()
    {
    }

    protected virtual void OnDestroy()
    {
        if (TSingleton<T>.ms_Singleton == this as T)
        {
            Destroy(base.gameObject);
            if (!Application.isEditor)
            {
                TSingleton<T>.ms_Singleton = null;
            }
        }
    }

    //--------------------------------------------------------------------------------------------

    protected void Delay(Action action, float time)
    {
        this.StartCoroutine(Delay_Enumerator(action, time));
    }

    protected void Delay<K, U>(Action<K, U> action, float time, K k, U u)
    {
        this.StartCoroutine(Delay_Enumerator<K, U>(action, time, k, u));
    }

    private IEnumerator Delay_Enumerator(Action action, float time)
    {
        yield return new WaitForSeconds(time);
        if (action != null)
        {
            action();
            action = null;
        }
    }

    private IEnumerator Delay_Enumerator<K, U>(Action<K, U> action, float time, K k, U u)
    {
        yield return new WaitForSeconds(time);
        if (action != null)
        {
            action(k, u);
            action = null;
        }
    }

    //--------------------------------------------------------------------------------------------

    private static void InstantiateMissingSingleton(Type myType)
    {
        GameObject obj2 = new GameObject(typeof(T).Name);
        ms_Singleton = obj2.AddComponent(typeof(T)) as T;
    }
}

public class SingletonBase : MonoBehaviour
{
    protected virtual void Start()
    {

    }
}

